package com.elock.service.serviceImpl;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.elock.base.core.Filter;
import com.elock.base.core.entity.Principal;
import com.elock.base.core.service.impl.BaseServiceImpl;
import com.elock.base.core.util.WebUtils;
import com.elock.dao.CompanyInfoDao;
import com.elock.entity.CompanyInfo;
import com.elock.entity.SaleOrg;
import com.elock.entity.SystemDict;
import com.elock.entity.SystemParameter;
import com.elock.service.CompanyInfoService;
import com.elock.service.MemberService;
import com.elock.service.PcRoleBaseService;
import com.elock.service.SaleOrgBaseService;
import com.elock.service.SystemDictBaseService;
import com.elock.service.SystemParameterBaseService;

@Service("companyInfoServiceImpl")
public class CompanyInfoServiceImpl extends BaseServiceImpl<CompanyInfo>
		implements CompanyInfoService {

	@Resource(name = "companyInfoDao")
	private CompanyInfoDao companyInfoDao;
	@Resource(name = "saleOrgBaseServiceImpl")
	private SaleOrgBaseService saleOrgBaseService;
	@Resource(name = "memberServiceImpl")
	private MemberService memberService;
	@Resource(name = "pcRoleBaseServiceImpl")
	private PcRoleBaseService pcRoleBaseService;
	@Resource(name = "systemParameterBaseServiceImpl")
	private SystemParameterBaseService systemParameterBaseService;
	@Resource(name = "systemDictBaseServiceImpl")
	private SystemDictBaseService systemDictBaseService;

	private static final String[] IGNORE_PROPERTIES = new String[] { "id",
			"createDate",
			"modifyDate",
			"parent",
			"children" };

	@Override
	@Transactional(readOnly = true)
	public CompanyInfo getCurrent() {

		Principal principal = WebUtils.getPrincipal();
		if (principal != null) {
			return find(principal.getCompanyinfoid());
		}
		return null;
	}

	@Override
	@Transactional(readOnly = true)
	public Long getCurrentId() {

		Principal principal = WebUtils.getPrincipal();
		if (principal != null) {
			return principal.getCompanyinfoid();
		}
		return null;
	}

	@Override
	@Transactional
	public void saveCompanyInfo(CompanyInfo companyInfo) {

		//设置企业属性，保存企业
		companyInfo.setActivateCode(generateCode());
		companyInfo.setCreate_by(memberService.getCurrent().getUsername());
		save(companyInfo);

		//初始化默认组织
		initSaleOrg(companyInfo);

		//初始化系统参数
		initSystemParameter(companyInfo);

		//初始化系统词汇
		initSystemDict(companyInfo);
	}

	@Override
	@Transactional
	public void updateCompanyInfo(CompanyInfo companyInfo) {

		//设置企业属性
		companyInfo.setUpdate_by(memberService.getCurrent().getUsername());
		update(companyInfo);

		//若修改了企业名称则修改默认组织名称
		List<Filter> filters = new ArrayList<Filter>();
		filters.add(Filter.eq("isTop", true));
		filters.add(Filter.eq("companyInfoId", companyInfo.getId()));
		SaleOrg saleOrg = saleOrgBaseService.find(filters);
		String company_name = companyInfo.getCompany_name();
		if (!saleOrg.getName().equals(company_name)) {
			saleOrg.setName(company_name);
			saleOrgBaseService.update(saleOrg);
		}
	}

	/**
	 * 初始化默认组织
	 * @param companyInfo
	 * @return
	 */
	public SaleOrg initSaleOrg(CompanyInfo companyInfo) {
		SaleOrg saleOrg = new SaleOrg();
		saleOrg.setName(companyInfo.getCompany_name());
		saleOrg.setIsTop(true);
		saleOrg.setIsEnabled(true);
		saleOrg.setIsLeaf(true);
		saleOrg.setCompanyInfoId(companyInfo.getId());
		saleOrgBaseService.save(saleOrg);
		return saleOrg;
	}

	/**
	 * 初始化系统参数
	 * @param companyInfo
	 */
	public void initSystemParameter(CompanyInfo companyInfo) {

		List<Filter> filters = new ArrayList<Filter>();
		filters.add(Filter.isNull("companyInfoId"));
		List<SystemParameter> systemParameters = systemParameterBaseService.findList(null,
				filters,
				null);
		if (!systemParameters.isEmpty()) {
			for (SystemParameter systemParameter : systemParameters) {
				SystemParameter parameter = new SystemParameter();
				parameter.setName(systemParameter.getName());
				parameter.setCode(systemParameter.getCode());
				parameter.setValue(systemParameter.getValue());
				parameter.setRemark(systemParameter.getRemark());
				parameter.setCompanyInfoId(companyInfo.getId());
				systemParameterBaseService.save(parameter);
			}
		}
	}

	/**
	 * 初始化系统词汇
	 * @param companyInfo
	 */
	public void initSystemDict(CompanyInfo companyInfo) {

		List<Filter> filters = new ArrayList<Filter>();
		filters.add(Filter.isNull("companyInfoId"));
		filters.add(Filter.isNull("parent"));
		List<SystemDict> aSystemDicts = systemDictBaseService.findList(null,
				filters,
				null);
		Long companyInfoId = companyInfo.getId();
		for (SystemDict systemDict : aSystemDicts) {

			//创建上级词汇
			SystemDict parentDict = new SystemDict();
			BeanUtils.copyProperties(systemDict, parentDict, IGNORE_PROPERTIES);
			parentDict.setCompanyInfoId(companyInfoId);
			systemDictBaseService.save(parentDict);

			//创建下级词汇
			filters.clear();
			filters.add(Filter.eq("parent", systemDict));
			List<SystemDict> cSystemDicts = systemDictBaseService.findList(null,
					filters,
					null);
			for (SystemDict cSystemDict : cSystemDicts) {
				SystemDict childDict = new SystemDict();
				BeanUtils.copyProperties(cSystemDict, childDict, IGNORE_PROPERTIES);
				childDict.setParent(parentDict);
				childDict.setCompanyInfoId(companyInfoId);
				systemDictBaseService.save(childDict);
			}
		}
	}

	/**
	 * 生成唯一、随机编码
	 * @return
	 */
	public String generateCode() {
		String sn = null;
		do {
			sn = randNum(5);
		}
		while (exists(Filter.eq("activateCode", sn)));

		return sn.toString();
	}

	/**
	 * 根据设定的长度随机生成序列
	 * @param len
	 * @return
	 */
	private String randNum(int len) {
		if (len == 0) return null;
		Random random = new Random();
		StringBuilder sn = new StringBuilder();
		for (int i = 0; i < len; i++) {
			sn.append(random.nextInt(10));
		}
		return sn.toString();
	}
}
